<template>
  <v-page full>
    <div class="page-wrap">
      <div ref="Vpage" class="main" id="v-page">
        <div id="anchors">
          <!-- 基础信息 -->
          <Card class="v-anchor">
            <BaseForm ref="baseForm" v-model:data="formModel.base" :isEdit="isEdit" @change="handleBaseChange" @initTable="initTable" :formModel="formModel" />
          </Card>
          <Card class="v-anchor" title="商品信息">
            <ProductsTable :data="formModel.products" ref="productTable" :skuParams="formModel.base" :isEdit="isEdit" :currency="currency" @changInput="changInput" :formModel="formModel" />
          </Card>
          <Card class="v-anchor">
            <CustomForm ref="customForm" :country="countryOptions" :data="formModel.recipient" />
          </Card>
          <Card class="v-anchor">
            <SenderForm ref="senderForm" :country="countryOptions" :data="formModel.sender" />
          </Card>
          <Card class="v-anchor">
            <PaymentForm ref="paymentForm" v-model:data="formModel.payment" @changInput="changInput" :orderAmount="orderAmount" :formModel="formModel" />
          </Card>
          <!-- 备注信息 -->
          <Card class="v-anchor">
            <RemarkFrom ref="RemarkForm" :data="formModel.base" :isEdit="isEdit" />
          </Card>

          <!-- 附件 -->
          <Card class="v-anchor" title="附件信息">
            <Accessory ref="AccessoryRef" :data="formModel.attachment" :isEdit="isEdit" />
          </Card>
        </div>
      </div>
      <div class="side-navigation">
        <div class="broadside">
          <div :class="['broadside-item cursor-pointer', index == sideActive ? 'active' : '']" v-for="(item, index) in sideNavigationData" :key="index" @click="scrollTop(index)">{{ item.label }}</div>
        </div>
        <div>
          <div class="mt-3 roll" :class="sideActive == 0 ? 'active' : ''" @click="toTop">
            <svg-icon class="text-white text-3xl" :icon-class="sideActive < 1 ? 'top' : 'top_on'"></svg-icon>
          </div>
          <div class="mt-3 roll" @click="toDown">
            <svg-icon class="text-white text-3xl" :icon-class="sideActive >= 5 ? 'down' : 'down_on'"></svg-icon>
          </div>
        </div>
      </div>
    </div>
    <div class="buttonBox shadow-2xl">
      <el-button @click="handleCancel"> 取消 </el-button>
      <el-button type="primary" @click="handleSave" v-if="saveBtn">保存</el-button>
    </div>
  </v-page>
</template>

<script setup name="UserListEdit">
import { ElMessage } from "element-plus"
import Card from "./components/Card/index.vue"
// 基础信息
import BaseForm from "./components//BaseForm/index.vue"
const baseForm = ref()
import ProductsTable from "./components/ProductsTable/index.vue"
const productTable = ref()
import CustomForm from "./components/CustomerForm/index.vue"
const customForm = ref()
import SenderForm from "./components/SenderForm/index.vue"
const senderForm = ref()
import PaymentForm from "./components/PaymentForm/index.vue"
const paymentForm = ref()

import Accessory from "./components/Accessory/index.vue"
const AccessoryRef = ref()

// 备注信息
import RemarkFrom from "./components/RemarkForm/index.vue"
const RemarkForm = ref()
import { SAVE_KEYS } from "./config"

import goodsApi from "@/components/SelectProduct/api"

import action from "@/utils/action.js"

import { getCountry, getCountryOption } from "@/api/public.js"
import api from "./api/index"

const router = useRouter()

const Vpage = ref()
const baseFormModel = ref({})
const saveBtn = ref(true)
const sideNavigationData = ref([{ label: "基础信息" }, { label: "商品信息" }, { label: "客户信息" }, { label: "寄件人信息" }, { label: "支付信息" }, { label: "备注信息" }])
const data = reactive({
  scrollNode: "",
  scrollNodeY: "",
  parentNode: "",
  sideActive: 0,
  anchorsList: [],
  countryOptions: [],
  attachment: [{}],
})

const currency = ref("USD")
const orderAmount = ref("")
//  组件待优化
const changInput = async ({ key, value }) => {
  if (key == "orderAmount") {
    if (formModel.base.build_order_type == 0) return
    if (paymentForm.value && paymentForm.value.form) {
      let data = paymentForm?.value?.form?.getFormValues()
      data.order_amount = Number(value)
      data.shipping_revenue = data.shipping_revenue || ""
      data.discount_amount = data.discount_amount || ""
      data.original_order_amount = (data.order_amount + Number(data.shipping_revenue) - Math.abs(data.discount_amount) || 0).toFixed(2)
      paymentForm?.value?.form?.setFormValues(data)
    }
  }
  if (key == "currency") {
    currency.value = value
  }
}

const formModel = reactive({
  base: {},
  items: [],
  payment: {
    original_order_currency: "",
    pay_amount: 0,
    payment_mode: 1,
    // shipping_revenue: 0,
  },
  recipient: {},
  attachment: [{}],
})
const { scrollNode, scrollNodeY, parentNode, sideActive, anchorsList, countryOptions } = toRefs(data)

onMounted(() => {
  nextTick(() => {
    handleGetCountry()
    handleGetDetail()
    scrollNode.value = document.getElementById("v-page")
    scrollNodeY.value = scrollNode.value.getBoundingClientRect().y - 1
    parentNode.value = document.getElementById("anchors")
    Vpage.value.addEventListener("scroll", handleScroll)
    update()
  })
})

// 待优化
watch(
  () => router.currentRoute.value.query,
  (val, oldVal) => {
    const { id, type } = val || {}
    if (type == "add") {
      return
    }
    if (pageType.value != type) return
    if (type == "edit") {
      if (id && pageId.value && id != pageId.value) {
        handleGetDetail()
      }
    }
    if (type == "copy") {
      if (id && pageId.value && id != pageId.value) {
        handleGetDetail()
      }
    }
  }
)

// onBeforeUnmount(() => {
//   Vpage.value.removeEventListener("scroll", handleScroll)
// })

import keepAliveStore from "@/store/modules/keepalive"
const keepStore = keepAliveStore()
const routerName = router.currentRoute.value.name
watch(
  () => keepStore.currentKeepAliveList,
  (val) => {
    if (!val.includes(routerName)) {
      Vpage.value.removeEventListener("scroll", handleScroll)
    }
  }
)

onActivated(() => {
  nextTick(() => {}).then(() => {
    let anchorElement = document.querySelectorAll(".v-anchor")[sideActive.value || 0]
    let offsetTop = anchorElement.offsetTop - 20
    Vpage.value.scrollTop = offsetTop
  })
})
const isEdit = computed(() => {
  const { id } = formModel.base
  return !!id
})

const handleBaseChange = (e) => {
  const { shop_id, platform } = e.shopCascade || {}
  baseFormModel.value.platform = platform
  baseFormModel.value.shop_id = shop_id
}
const generateRandomNumber = () => {
  let randomNumber = Math.floor(Math.random() * 100000)
  return String(randomNumber).padStart(5, "0")
}
const initTable = async (e) => {
  // console.log(e);
  
  if (e == 4) {
    let res = await api.orderCreateDefault()
    let { data } = await goodsApi.query({ sku: res?.data?.products?.[0]?.sku })
    // console.log("initTable")
    // console.log(data)
    formModel.products = data.map((n, idx) => ({
      order_item_id: generateRandomNumber(),
      main_img: n.attr_img,
      sku: n.sku,
      custom_sku: n.custom_sku,
      sku_cn_title: n.sku_cn_title,
      shipping_logistics_attr: n.shipping_logistics_attr || "-",
      quantity: 1,
      original_amount: 0,
      available_stock: 0,
      purchase_price: n.purchase_price,
      platform_sku: "1",
      original_price: 0,
      total: 0,
    }))

    formModel.recipient = {
      ...formModel.recipient,
      ...res?.data.recipient,
    }

    formModel.base = {
      ...formModel.base,
      ...res?.data.order,
    }
    formModel.payment = {
      ...formModel.payment,
      original_order_currency: "CNY",
    }
  }

  if (e == 6) {
    // console.log(formModel);
    let products = productTable.value.getTableData().tableData
    formModel.products = products.map((n, idx) => ({
      ...n,
      original_price: 0,
    }))
  }

  // console.log("formModel")
  // console.log(formModel)
}

const pageType = ref("")
const pageId = ref("")
const handleGetDetail = async () => {
  const { id, type } = router.currentRoute.value.query || {}
  pageType.value = type
  if (!id || id === "add") return
  try {
    const { data } = await api.orderDetail({ id })
    let { recipient, logistics, payment, sender, items, ...base } = data || {}
    pageId.value = base.id || ""
    currency.value = data.original_order_currency
    formModel.base = Object.assign(base, {
      // 新建订单原因 数据类型不对  为0则清空数据
      new_order_reason: base?.new_order_reason != 0 ? base?.new_order_reason : "",
      // 销售人员
      sales_id: base?.sales_id?.[0] || "",
    })

    formModel.payment = {
      ...payment,
      // 造成多余数据   待优化
      ...base,
      shipping_revenue: base?.shipping_revenue,
      discount_amount: Math.abs(base?.discount_amount),
    }

    if (type == "copy") {
      // id  新建订单原因
      delete formModel.base.id
      // formModel.base.new_order_reason = ""
      // 不复置发货时间
      formModel.base.shipping_time = ""

      formModel.payment.original_order_amount = 0
      formModel.payment.order_amount = 0
      formModel.payment.shipping_revenue = 0
      formModel.payment.discount_amount = 0
      // 订单创建类型
      formModel.payment.build_order_type = 1

      formModel.base.origin_order_sn = formModel.base.order_sn

      items.forEach((item) => {
        item.original_price = 0
      })
      // 保存原单的买家姓名ID
      // formModel.base.clientele_id = formModel.base.platform_buyer_id
      // ebay 订单  填充 平台买家ID
      // if (formModel.base.platform_id == 1) {
      // formModel.base.buyer_name = recipient.buyer_name
      // }
    }
    // 平台买家ID
    formModel.base.buyer_name = recipient.buyer_name
    formModel.products = items

    formModel.sender = sender
    // recipient.recipient_country = recipient.recipient_country_id
    formModel.recipient = recipient
    formModel.attachment = data.attachment || [{}]
    // 去验证 待优化
    setTimeout(() => {
      baseForm?.value?.form?.submit()
    }, 500)
    // 亚马逊，FBA订单不允许修改订单信息
    if (type == "edit" && data.platform_id == 2 && data.shipping_type == 1) {
      saveBtn.value = false
    }
  } catch (e) {
    console.error(e)
  }
}

const handleGetCountry = async () => {
  try {
    const { data } = await getCountryOption()
    countryOptions.value = data.map((v) => ({
      label: `${v.name} ${v.country}`,
      value: v.country,
      id: v.id,
    }))
  } catch (e) {
    console.error(e)
  }
}

const handleCancel = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  })
}

const handleSave = async () => {
  try {
    const { id } = formModel.base

    // const { shopCascade, ...base } = await baseForm.value.form.submit()
    const { ...base } = await baseForm.value.form.submit()
    const tableData = productTable.value.getTableData().tableData
    // console.log(tableData)
    if (!tableData?.length) {
      ElMessage.warning("请选择商品!")
      return
    }
    const _emptySku = tableData.findIndex((n) => !n.sku)
    if (_emptySku > -1) {
      ElMessage.warning(`请补充第${_emptySku + 1}个商品sku信息!`)
      return
    }
    const _emptyPlatformSku = tableData.findIndex((n) => !n.platform_sku)
    if (_emptyPlatformSku > -1) {
      ElMessage.warning(`请补充第${_emptyPlatformSku + 1}个商品渠道sku信息!`)
      return
    }
    if (base.new_order_reason == 5 && tableData.find((v) => v.original_price == 0)) {
      ElMessage.warning(`线下订单的产品单价不能为0！`)
      return
    }

    const custom = await customForm.value.form.submit()
    for (const key in custom) {
      typeof custom[key] == "string" && (custom[key] = custom[key]?.trim())
    }

    const sender = await senderForm.value.form.submit()

    const payment = await paymentForm.value.form.submit()

    await RemarkForm.value.form.submit()

    const recipientCountry = countryOptions.value.find((n) => n.value === custom?.recipient_country)
    // console.log(recipientCountry)
    const senderCountry = countryOptions.value.find((n) => n.value === sender?.sender_country)
    payment.payer = custom.recipient_name
    const params = {
      id: isEdit.value ? id : undefined,
      order: {
        ...base,
        // ...shopCascade,
        shipping_revenue: payment?.shipping_revenue || 0,
        discount_amount: -Math.abs(payment?.discount_amount),
        original_order_currency: payment?.original_order_currency,
        order_amount: payment?.order_amount,
        original_order_amount: payment?.original_order_amount,
        attachment: formModel.attachment,
      },
      recipient: {
        ...custom,
        recipient_country: recipientCountry?.value,
        recipient_country_id: recipientCountry?.id,
      },
      // 寄件人信息
      sender: {
        ...sender,
        sender_country: senderCountry?.label,
        sender_country_id: senderCountry?.id,
        sender_door_num: String(sender.sender_door_num || ""),
      },
      payment,
      products: tableData,
    }
    // 新建订单原因 默认 0
    params.order.new_order_reason = params.order.new_order_reason || 0

    // 销售人员
    params.order.sales_id = base.sales_id ? [base.sales_id] : []

    if (params.order.attachment.find((v) => !v.type && v.name)) {
      return ElMessage({ showClose: true, message: "文件类型必填！", type: "warning" })
    }

    params.order.attachment = params.order.attachment?.filter((v) => v.name) || []
    let origin_order_sn = params.order.origin_order_sn
    for (const key in SAVE_KEYS) {
      if (SAVE_KEYS[key].type == "object") {
        params[key] = Object.fromEntries(SAVE_KEYS[key].key.map((v) => [v, params[key][v]]))
      }
      if (SAVE_KEYS[key].type == "array") {
        params[key] = params[key].map((item) => Object.fromEntries(SAVE_KEYS[key].key.map((v) => [v, item[v]])))
      }
    }
    if (router.currentRoute.value.query?.type == "copy") {
      params.order.platform_buyer_id = base.platform_buyer_id
      // 原平台订单号
      params.order.origin_order_sn = origin_order_sn
      // 平台买家ID
      params.recipient.buyer_name = base.buyer_name
    }

    if (params.order.new_order_reason == 4 && !isEdit.value) {
      params?.products?.forEach((item) => {
        item.sales_id = params.order.sales_id?.[0]
      })
    }
    const apiConfig = {
      edit: api.updateDetail,
      add: api.createOrder,
    }
    // console.log(params)
    // return
    const res = await apiConfig[isEdit.value ? "edit" : "add"](params)
    if (res.message === "success") {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: "closeActiveTab",
        },
      })
    }
  } catch (e) {
    console.warn(e)
  }
}

const update = () => {
  nextTick(() => {
    if (!parentNode.value) return
    anchorsList.value = Array.from(parentNode.value.querySelectorAll(".v-anchor"))
    handleScroll()
  })
}

const scrollTop = (index) => {
  nextTick(() => {
    let anchorElement = document.querySelectorAll(".v-anchor")[index]
    let offsetTop = anchorElement.offsetTop - 20
    Vpage.value.scrollTo({ top: offsetTop, behavior: "smooth" })
  })
}

const handleScroll = () => {
  sideActive.value = anchorsList.value.findIndex((d) => d.getBoundingClientRect().y > scrollNodeY.value)
}

const toDown = () => {
  Vpage.value.scrollTo({ top: Vpage.value.scrollHeight, behavior: "smooth" })
  setTimeout(() => {
    sideActive.value = 5
  }, 900)
}
//滚动到顶部
const toTop = () => {
  Vpage.value.scrollTo({ top: 0, behavior: "smooth" })
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
